/*
	PlAr is Platform Arena: a 2D multiplayer shooting game
	Copyright (c) 2010, Antonio Ragagnin <spocchio@gmail.com>
    All rights reserved.

    This file is licensed under the New BSD License.
*/

package res.elements;

import plar.core.Element;
import plar.core.Action;
import plar.core.Common;
import plar.core.ActionNoGravity;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.Body;

public class Platform extends Element {
    public Vec2 sensibiliy;
    public Vec2 centralPosition;
    public Vec2 returnSpeedFactor;
    public Vec2 returnPositionFactor;
    public float returnAngleFactor;
    public float returnAngularSpeedFactor;

    class AdjustPlayer extends Action {

        public void run() {

            if(centralPosition.x==0) {
                centralPosition.x=me.getPosition().x;
                centralPosition.y=me.getPosition().y;
            }
            Vec2 currentPosition = me.getPosition();

            Vec2 delta = new Vec2(-currentPosition.x + centralPosition.x,
                                  -currentPosition.y + centralPosition.y);
            if (Math.abs(delta.x) > sensibiliy.x
                    || Math.abs(delta.y) > sensibiliy.y) {

                me.body
                .applyForce(
                    new Vec2(
                        me.body.getMass()
                        * (returnPositionFactor.x
                           * delta.x - returnSpeedFactor.x
                           * getSpeed().x)/
                        me.level.Dt,
                        me.body.getMass()
                        * (returnPositionFactor.y
                           * delta.y - returnSpeedFactor.y
                           * getSpeed().y)/
                        me.level.Dt),
                    me.body.getWorldCenter());

            }

            //me.body.applyTorque(me.body.getMass()*(-returnAngleFactor*me.getAngle()-returnAngularSpeedFactor*me.body.getAngularVelocity())/me.level.Dt);

        }

    }

    public Platform() {
        super();
        isRunnable = true;
        sensibiliy = new Vec2(1f, 0.5f);
        centralPosition = new Vec2(0, 0);
        //returnPositionFactor = new Vec2(100f, 100f);
        //returnSpeedFactor = new Vec2(10f, 10f);
        returnAngleFactor = 0.05f;
        density=10;
        friction=0;
        returnAngularSpeedFactor = 0.05f;

        returnPositionFactor = new Vec2(1f, 1f);
        returnSpeedFactor = new Vec2(0.5f, 0.5f);

        setStaticSprite("res/elements/elevator.png");

        actions.addAction("adjust", new AdjustPlayer());
        actions.addAction("nogravity", new ActionNoGravity());

    }

    public void setBody(Body b)
    {
        super.setBody(b);
        //	b.setFixedRotation(false);
        //b.setAngularDamping(10f);
        b.setLinearDamping(1.0f);
    }
    public void setBodyDef(BodyDef bd) {

        bd.type = BodyType.DYNAMIC;

    }

}
